package com.dada.controller;

import com.dada.util.CommonUtil;
import com.google.code.kaptcha.Producer;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/account/v1")
@RequiredArgsConstructor
@Slf4j
public class NotifyController {
  private final Producer captchaProducer;
  private final StringRedisTemplate redisTemplate;
  private static final long CAPTCHA_EXPIRE = 1000 * 60 * 2;

  /**
   * 生成验证码
   * @param request request
   * @param response response
   */
  @GetMapping("captcha")
  public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
    String text = captchaProducer.createText();
    //存储验证码到redis
    redisTemplate.opsForValue().set(getCaptchaKey(request), text, CAPTCHA_EXPIRE,
        TimeUnit.MILLISECONDS);
    log.info("验证码：{}", text);
    BufferedImage image = captchaProducer.createImage(text);
    try (ServletOutputStream outputStream = response.getOutputStream()){
      ImageIO.write(image, "jpg", outputStream);
    }catch (IOException e){
      log.error("验证码图像流处理失败{}", e);
    }
  }

  private String getCaptchaKey(HttpServletRequest request){
    String ipAddr = CommonUtil.getIpAddr(request);
    String userAgent = request.getHeader("User-Agent");
    String key = "account-service:captcha"+CommonUtil.MD5(ipAddr+userAgent);
    log.info("验证码key：{}", key);
    return key;
  }
}
